﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccess;
using Entities;

namespace Controller
{
    public class GetQueryInformationController
    {
        public event GetQueryInformationEventHandler GetQueryInformationCompleted;

        public void OnGetQueryInformationCompleted(GetQueryInformationEventArgs e)
        {
            if (GetQueryInformationCompleted != null)
            {
                GetQueryInformationCompleted(e);
            }
        }
        public void GetQueryInformation(ConnectionInformation CI, string QueryString)
        {
            
            TableInformation result = new TableInformation();

            QueryString = QueryString.Trim();
            QueryString = QueryString.ToLower();

            if (string.IsNullOrEmpty(QueryString))
            {
                OnGetQueryInformationCompleted(new GetQueryInformationEventArgs(new Exception("Please write valid query in Query area. It must not be empty.")));
            }
            else if (!QueryString.StartsWith("select"))
                OnGetQueryInformationCompleted(new GetQueryInformationEventArgs(new Exception("Only select query allowed.")));
            else
            {
                try
                {
                    if (CI.DataBaseType == DataBaseType.MSSQLServer)
                    {
                        MSSQLDataAccess mSSQLDataAccess = new MSSQLDataAccess();
                        result = mSSQLDataAccess.QueryValidation(CI, QueryString);
                    }
                    else if (CI.DataBaseType == DataBaseType.MSAccess)
                    {
                        MSAccessDataAccess mSAccessDataAccess = new MSAccessDataAccess();
                        result = mSAccessDataAccess.QueryValidation(CI, QueryString);
                    }
                    else if (CI.DataBaseType == DataBaseType.MySQL)
                    {
                        MySQLDataAccess mySQLDataAccess = new MySQLDataAccess();
                        result = mySQLDataAccess.QueryValidation(CI, QueryString);
                    }


                    OnGetQueryInformationCompleted(new GetQueryInformationEventArgs(result));
                }
                catch (Exception ex)
                {
                    OnGetQueryInformationCompleted(new GetQueryInformationEventArgs(ex));        
                }
            }
        }
    }
}
